package com.maximus.server.nio;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;

public class ReadAndWrite {
    private static final Logger logger = LogManager.getLogger(ReadAndWrite.class);

    private static StringBuilder buffer = new StringBuilder();

    public static void readAndWrite(SocketChannel channel, ByteBuffer byteBuffer) throws IOException {

        int read = channel.read(byteBuffer);
        if (read > 0) {
            byteBuffer.flip();
            buffer.append(StandardCharsets.UTF_8.decode(byteBuffer));
            byteBuffer.clear();
            int index;

            while ((index = findLineEnd(buffer)) != -1) {
                String line = extractLine(buffer, index);
                logger.info("客户端：" + channel.getRemoteAddress() + "发来消息：" + line);
                // 回显该行（自动补上换行符）
                channel.write(ByteBuffer.wrap((line + "\r\n").getBytes(StandardCharsets.UTF_8)));
            }
        } else {
            throw new IOException();
        }

    }
    private static int findLineEnd(StringBuilder buffer) {
        String data = buffer.toString();
        int rnIndex = data.indexOf("\r\n");
        if (rnIndex != -1) return rnIndex + 2; // 包括\r\n的长度
        int nIndex = data.indexOf("\n");
        if (nIndex != -1) return nIndex + 1;    // 包括\n的长度
        return -1;
    }

    private static String extractLine(StringBuilder buffer, int endIndex) {
        String line = buffer.substring(0, endIndex).trim();
        buffer.delete(0, endIndex);
        return line;
    }
}
